from rest_framework.viewsets import ModelViewSet
from fdfs_client.client import Fdfs_client
from meiduo_admin.brands.brand_serializers import GoodsBrandsSerializers
from meiduo_admin.my_paginate import MyPageNuberPagination
from goods.models import Brand
from rest_framework.response import Response
from django.conf import settings


class GoodsBrandsView(ModelViewSet):
    pagination_class = MyPageNuberPagination
    serializer_class =GoodsBrandsSerializers
    queryset = Brand.objects.all()

    # 2,重写create方法,保存新增图片数据
    def create(self, request, *args, **kwargs):
        #获取参数
        name=request.data.get("name")
        first_letter=request.data.get("first_letter")
        logo=request.FILES.get("logo")

        # 2,校验参数
        if not all([name,first_letter,logo]):
            return Response(status=400)

        # 3,数据入库
        client=Fdfs_client(settings.FDFS_CONFIG)
        ret=client.upload_by_buffer(logo.read())
        # 3,1判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 3,2数据入库图片
        image_url=ret.get("Remote file_id")
        Brand.objects.create(name=name,first_letter=first_letter,logo=image_url)

        return Response(status=201)

    # 图片表修改,重写update方法,修改图片
    def update(self, request, *args, **kwargs):

        #获取参数
        name=request.data.get("name")
        first_letter = request.data.get("first_letter")
        logo=request.FILES.get("logo")
        pk=self.kwargs.get("pk")
        #2.校验数据
        if not all([name,first_letter,logo]):
            return  Response(status=400)

          # 3,数据入库到storage容器的fdfs
        client=Fdfs_client(settings.FDFS_CONFIG)
        ret=client.upload_by_buffer(logo.read())

        # 3,1判断图片是否入库成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 3,2数据入库
        image_url=ret.get("Remote file_id")
        Brand.objects.filter(id=pk).update(name=name,first_letter=first_letter,logo=image_url)


        return Response(status=201)


